package org.atlantis.net.base.vote;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Arrays;

/*
 * 投票UDP客户端。
 * 注：UDP客户端发送数据时不需要对数据进行装帧操作，因为UDP的数据报文自带边界标识。
 */
public class VoteClientUDP {

	public static final String SERVER_HOST = "127.0.0.1";
	public static final int SERVER_PORT = 10006;

	public static void main(String[] args) throws Exception {
		InetAddress serverAddr = InetAddress.getByName(SERVER_HOST);
		DatagramSocket socket = new DatagramSocket();
		// 通过调用connect方法，就不必再为发送的每个数据报文指定远程地址和端口，也不必测试服务器回执报文数据的源地址是否正确
		socket.connect(serverAddr, SERVER_PORT);

		// 创建投票信息
		VoteMessage message = new VoteMessage(false, false, 888, 0);
		VoteMessageCoder coder = new VoteMessageBinCoder();

		byte[] encodedVote = coder.encode(message);
		DatagramPacket packetMessage = new DatagramPacket(encodedVote,
				encodedVote.length);

		// 发送投票请求
		socket.send(packetMessage);

		// 接收服务器回执信息
		packetMessage = new DatagramPacket(
				new byte[VoteMessageTextCoder.MAX_WIRE_LENGTH],
				VoteMessageTextCoder.MAX_WIRE_LENGTH);
		socket.receive(packetMessage);
		encodedVote = Arrays.copyOfRange(packetMessage.getData(), 0,
				packetMessage.getLength());

		System.out.println("从服务器接收到反馈信息：");
		message = coder.decode(encodedVote);
		System.out.println(message);
	}
}
